<?php

/*
 *  Copyright (c) Nicholas Mossor Rathmann <nicholas.rathmann@gmail.com> 2007-2009. All Rights Reserved.
 *
 *
 *  This file is part of OBBLM.
 *
 *  OBBLM is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  OBBLM is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */
 
function aasort(&$array, $args) {

    $sort_rule = ""; # Must be initialized in outer scope.
    foreach($args as $arg) {
        $order_field = substr($arg, 1, strlen($arg));
        foreach($array as $array_row) {
            $sort_array[$order_field][] = $array_row[$order_field];
        }
        $sort_rule .= '$sort_array["'.$order_field.'"], '.($arg[0] == "+" ? SORT_ASC : SORT_DESC).',';
    }
    eval ("array_multisort($sort_rule".' $array);');
}

// Sorts array of objects by common object properties. 
// Usage: objsort($obj_array, array('+X', '-Y')) ...to sort objects by X ascending followed by Y descending.
function objsort(&$obj_array, $fields)
{
    $idxs = count($fields)-1;   # Number of fields to sort by.
    $func = 'return ';          # Anonymous function used for sorting the object array.
    $parens = 0;                # Number of parentheses added to end of anonymous function.
    
    for ($i = 0; $i <= $idxs; $i++) {
        $field = substr($fields[$i], 1, strlen($fields[$i]));
        $sort_type = substr($fields[$i], 0, 1);
        $parens += ($i == $idxs ? 1 : 2);
        $func .= "\$a->$field " . ($sort_type == '+' ? '>' : '<') . " \$b->$field 
                    ? 1 
                    : (\$a->$field != \$b->$field 
                        ? -1 
                        : " . ($i == $idxs ? '0' : '(');
    }

    $func .= str_repeat(')', $parens) . ';';
    return usort($obj_array, create_function('$a, $b', $func));
}

/**
 * sort_rule function.
 * Returns what sort rule is to be used for different stats-table types.
 * 
 * @access public
 * @param mixed $w
 * @return void
 */
function sort_rule($w) {
    
    $rule = array();
    
    switch ($w)
    {
        case 'streaks': // For streaks table.
            $rule = array('-row_won', '-row_draw', '+row_lost', '+name');
            break;
    
        case 'race_page': // Race's players table.
            $rule = array('+cost', '+position');
            break;
            
        case 'race': // "All races"-table
            $rule = array('-win_percentage', '+race');
            break;
            
        case 'match': // Games played tables.
            $rule = array('-date_played');
            break;
    
        case 'coach': // "All coaches"-table
            $rule = array('-win_percentage', '-won_tours', '-cas', '+name');
            break;
            
        case 'team': // Overall team standings.
            $rule = array('-won', '-draw', '+lost', '-score_diff', '-cas', '+name');
            break;
            
        case 'player': // For team roaster player list.
            $rule = array('+nr', '+name');
            break;
            
        case 'player_overall': // "All players"-table
            $rule = array('-value', '-td', '-cas', '-spp', '+name');
            break;
            
        case 'star': // Stars table.
            $rule = array('-played', '+name');
            break;
            
        case 'star_HH': // Stars hire history table.
            $rule = array('-date_played');
            break;
    }
    
    return $rule;
}


function rule_dict(array $rule) {
    
    /* Translates sort rules. */
    
    $d = array(
        'win_percentage'    => 'win percentage',
        'date_played'       => 'date played',
        'won_tours'         => 'won tours',
        'score_diff'        => 'score diff.',
        'tdcas'             => '{td+cas}',
        'row_won'           => 'won in row',
        'row_lost'          => 'lost in row',
        'row_draw'          => 'draw in row',
    );
    
    foreach ($rule as &$r) {
        $r = preg_replace('/_tour$/', '', $r);
        foreach ($d as $idx => $rpl) {
            $r = preg_replace("/$idx/", $rpl, $r);
        }
    }
    
    return $rule;
}


/**
 * pic_box function.
 * 
 * @access public
 * @param mixed $cur_img
 * @param bool $up_perm (default: false)
 * @param bool $suffix (default: false)
 * @return void
 */
function pic_box($cur_img, $up_perm = false, $suffix = false, $no_echo = false) {
    
    include_once("Mustache.php");
    $mus = new Mustache;
    
    $template = file_get_contents("templates/pic_box.ms");
    
    $data = array();
    
    $data["cur_img"] = $cur_img;
    
    if ($up_perm){
    	$data["up_perm"] = true;
    	$data["UPLOAD_DIR"] = UPLOAD_DIR;
    	
    	if (is_writable(UPLOAD_DIR)){
    		$data["is_writable"] = true;		
    		
    		if ($suffix){
    			$data["suffix"] = $suffix;
    		}
    	} 		
    }
    
    if ($no_echo){
    	return $mus->render($template, $data);
    } else {
    	echo $mus->render($template, $data);   
    }
}

function save_pic($fname, $path, $id) {

    if (isset($_FILES[$fname]['tmp_name'])) {
        if (!is_dir($path)) {
            mkdir($path);
        }
        $ext = '';
        switch ($_FILES[$fname]['type'])
        {
            case 'image/gif':  $ext = 'gif'; break;
            case 'image/jpeg': $ext = 'jpeg'; break;
            case 'image/jpg':  $ext = 'jpeg'; break;
            case 'image/png':  $ext = 'png'; break;
        }
        if ($ret = move_uploaded_file($_FILES[$fname]['tmp_name'], "$path/$id.$ext")) {
            foreach (array('gif', 'jpeg', 'jpg', 'png') as $t) {
                if ($t != $ext) {
                    @unlink("$path/$id.$t");
                }
            }
        }
    }
    else {
        return 3;
    }
    
    if (empty($ext)) {
        return 2;
    }
    elseif (!$ret) {
        return 1;
    }
    else {
        return 0; // OK!
    }
}

function get_pic($path, $id) {

    $p = "$path/$id.";
    
    if (file_exists($p.'gif')) return $p.'gif';
    elseif (file_exists($p.'jpeg')) return $p.'jpeg';
    elseif (file_exists($p.'jpg')) return $p.'jpg';
    elseif (file_exists($p.'png')) return $p.'png';
    else return NO_PIC;
}

// Prints page title for main section pages.
function title($title) {
    echo "<h2>$title</h2>\n";
}

// Privileges error. Stop PHP interpreter and warn the user!
function fatal($err_msg) {
    die("<br><br><center><big><font color='red'><b>$err_msg</b></font></big></center><br>");
}

// Print a status message.
function status($status, $msg = '') {

        if ($status) { # Status == success
            echo "<div class=\"messageContainer green\">";
                echo "Request succeeded";
                if ($msg != ''){
                    echo " : $msg\n";
                }
            echo "</div>";
        } else { # Status == failure
                echo "<div class=\"messageContainer red\">";
                    echo "Request failed";
                if ($msg != ''){
                    echo " : $msg\n";
                }
            echo "</div>";
        }
        ?>
    <?php
}

function textdate($mysqldate, $noTime = false) {
    return date("D M j Y".(($noTime) ? '' : ' G:i:s'), strtotime($mysqldate));
}

// Returns HTML to show an icon with the result of a game
function matchresult_icon($result) {

    global $lng;

    $class = "";

    switch ($result){
        case "W":
            $class = "won";
            $title = $lng->getTrn('global/misc/gamewon');
            break;
        case "L":
            $class = "lost";
            $title = $lng->getTrn('global/misc/gamelost');
            break;
        case "D":
            $class = "draw";
            $title = $lng->getTrn('global/misc/gamedraw');
            break;
        default:
            $class = "";
            $title = $lng->getTrn('global/misc/gameunknown');
    }
    return "<div class='match_icon ". $class ."' title='". $title ."'></div>";
}

/** Makes a var_dump of the given data var, and wraps it in pre tags to render it nicely in the browser
 *  Only outputs somethig if the url param "debug" is set 
 *  
 * @param mixed $var - variable to dump
 * $param bool $bypass - (optional) use this to bypass only outputting debug when the GET parm is set
 */
function debug($data){
	if (isset($_GET['debug'])) {
		dump($data);
	}
}


////////////////////////////////////////////////////////
// Function:         dump
// Inspired from:     PHP.net Contributions
// Description: Helps with php debugging

function dump(&$var, $info = FALSE)
{
    $scope = false;
    $prefix = 'unique';
    $suffix = 'value';
  
    if($scope) $vals = $scope;
    else $vals = $GLOBALS;

    $old = $var;
    $var = $new = $prefix.rand().$suffix; $vname = FALSE;
    foreach($vals as $key => $val) if($val === $new) $vname = $key;
    $var = $old;

    echo "<pre style='clear:both;margin: 0 0 10px 0;display:block;background: white; color: black; font-family: Verdana; border: 1px solid #ccc; padding: 5px; font-size: 10px; line-height: 13px;'>";
    if($info != FALSE) echo "<b style='color: red;'>$info:</b><br>";
    do_dump($var, '$'.$vname);
    echo "</pre>";
}

////////////////////////////////////////////////////////
// Function:         do_dump
// Inspired from:     PHP.net Contributions
// Description: Better GI than print_r or var_dump

function do_dump(&$var, $var_name = NULL, $indent = NULL, $reference = NULL)
{
    $do_dump_indent = "<span style='color:#eee;'>|</span> &nbsp;&nbsp; ";
    $reference = $reference.$var_name;
    $keyvar = 'the_do_dump_recursion_protection_scheme'; $keyname = 'referenced_object_name';

    if (is_array($var) && isset($var[$keyvar]))
    {
        $real_var = &$var[$keyvar];
        $real_name = &$var[$keyname];
        $type = ucfirst(gettype($real_var));
        echo "$indent$var_name <span style='color:#a2a2a2'>$type</span> = <span style='color:#e87800;'>&amp;$real_name</span><br>";
    }
    else
    {
        $var = array($keyvar => $var, $keyname => $reference);
        $avar = &$var[$keyvar];
    
        $type = ucfirst(gettype($avar));
        if($type == "String") $type_color = "<span style='color:green'>";
        elseif($type == "Integer") $type_color = "<span style='color:red'>";
        elseif($type == "Double"){ $type_color = "<span style='color:#0099c5'>"; $type = "Float"; }
        elseif($type == "Boolean") $type_color = "<span style='color:#92008d'>";
        elseif($type == "NULL") $type_color = "<span style='color:black'>";
    
        if(is_array($avar))
        {
            $count = count($avar);
            echo "$indent" . ($var_name ? "$var_name => ":"") . "<span style='color:#a2a2a2'>$type ($count)</span><br>$indent(<br>";
            $keys = array_keys($avar);
            foreach($keys as $name)
            {
                $value = &$avar[$name];
                do_dump($value, "['$name']", $indent.$do_dump_indent, $reference);
            }
            echo "$indent)<br>";
        }
        elseif(is_object($avar))
        {
            echo "$indent$var_name <span style='color:#a2a2a2'>$type</span><br>$indent(<br>";
            foreach($avar as $name=>$value) do_dump($value, "$name", $indent.$do_dump_indent, $reference);
            echo "$indent)<br>";
        }
        elseif(is_int($avar)) echo "$indent$var_name = <span style='color:#a2a2a2'>$type(".strlen($avar).")</span> $type_color$avar</span><br>";
        elseif(is_string($avar)) echo "$indent$var_name = <span style='color:#a2a2a2'>$type(".strlen($avar).")</span> $type_color\"$avar\"</span><br>";
        elseif(is_float($avar)) echo "$indent$var_name = <span style='color:#a2a2a2'>$type(".strlen($avar).")</span> $type_color$avar</span><br>";
        elseif(is_bool($avar)) echo "$indent$var_name = <span style='color:#a2a2a2'>$type(".strlen($avar).")</span> $type_color".($avar == 1 ? "TRUE":"FALSE")."</span><br>";
        elseif(is_null($avar)) echo "$indent$var_name = <span style='color:#a2a2a2'>$type(".strlen($avar).")</span> {$type_color}NULL</span><br>";
        else echo "$indent$var_name = <span style='color:#a2a2a2'>$type(".strlen($avar).")</span> $avar<br>";

        $var = $var[$keyvar];
    }
}